use std::collections::HashMap;

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    let left = num_str.find('(').unwrap();
    let right = num_str.len() - 1;
    let num_origin = &num_str[..left];

    let from_base = &num_str[left + 1..right].parse().unwrap();

    let char_to_value: HashMap<char, u32> = ('0'..='9')
        .chain('a'..'f')
        .enumerate()
        .map(|(i, c)| (c, i as u32))
        .collect();
    let mut decimal_num = 0u32;
    for c in num_origin.to_lowercase().chars() {
        if let Some(&value) = char_to_value.get(&c) {
            decimal_num = decimal_num * from_base + value;
        } else {
            panic!("Invalide character {} in base {}", c, from_base);
        }
    }

    let mut result = Vec::new();
    while decimal_num > 0 {
        let remainder = decimal_num % to_base;
        decimal_num /= to_base;
        result.push(if remainder < 10 {
            char::from_digit(remainder, 10).unwrap()
        } else {
            char::from_u32(('a' as u32) + remainder - 10).unwrap()
        })
    }

    if result.is_empty() {
        return '0'.to_string();
    }

    result.reverse();
    result.iter().collect::<String>()
}
